package com.denlaku.longan.util;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author tianx
 */
public final class Objects {
    public static boolean isNonNull(Object... values) {
        if (values != null) {
            for (Object value : values) {
                if (value == null) {
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean nonNull(Object value) {
        return value != null;
    }

    public static <T> T defaultIfNull(T value, T defaultValue) {
        return value != null ? value : defaultValue;
    }

    public static <T, R> R map(T t, Function<T, R> mapper) {
        return t == null ? null : mapper.apply(t);
    }

    public static <T, U, R> R map(T t, Function<T, U> mapper, Function<U, R> thenMapper) {
        return Optional.ofNullable(t).map(mapper).map(thenMapper).orElse(null);
    }

    public static <T> void ifPresent(T t, Consumer<T> consumer) {
        if (t != null) {
            consumer.accept(t);
        }
    }

    public static <T> void ifPresent(T t, Runnable applier) {
        if (t != null) {
            applier.run();
        }
    }

    public static <T> Optional<T> of(T t) {
        return Optional.ofNullable(t);
    }

    public static String toString(Object o) {
        return String.valueOf(o);
    }

    public static String toString(Object o, String nullDefault) {
        return o != null ? o.toString() : nullDefault;
    }

    public static boolean equals(Object a, Object b) {
        return java.util.Objects.equals(a, b);
    }
}
